import time

from django.shortcuts import render
from book.models import Book,loginUser
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse
from django.core import serializers
import json



def add_book(request):
    print("add_book2...")
    data = json.loads(request.body.decode("utf-8"))
    print(data) # post
    # print(request.GET.get('book_name'),request.GET.get('test')) # get
    response = {}
    if not data["book_name"]:
        response['msg'] = "please input book name!"
        response['error_num'] = 1
        return JsonResponse(response)
    try:
         Book.objects.create(**data)

         response['msg'] = 'success'
         response['error_num'] = 0
    except Exception as e:
         response['msg'] = str(e)
         response['error_num'] = 1


    return JsonResponse(response)

# @require_http_methods(["GET"])
def show_books(request):
     response = {}
     try:
         books = Book.objects.all().order_by("-add_time")
         response['list'] = json.loads(serializers.serialize("json", books))


         response['msg'] = 'success'
         response['error_num'] = 0
     except Exception as e:
         response['msg'] = str(e)
         response['error_num'] = 1

     return JsonResponse(response)

def login(request):
    print("logon....")
    data = json.loads(request.body.decode("utf-8"))
    # file = request.FILES.get("image")
    print(data)
    # print(file)
    # data = ''
    response = {}
    try:
        res = loginUser.objects.filter(name=data["username"],password=data["password"])
        print(res)
        if res:
            response['msg'] = "登陆成功"
            response['code'] = 0
            response['token'] = str(time.time())
            print(response)
            return JsonResponse(response)
        else:
            print("**12")
            response['msg'] = "用户名或密码错误"
            response['code'] = 1
            return JsonResponse(response)


    except Exception as e:
        print("**13")
        response['msg'] = str(e)
        response['code'] = 1

def getinfo(request):
    print("request*" * 10)
    # response = {"status":200,"name":"admin","token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoei5saWNhaW1vZmFuZy5jb20iLCJhdWQiOiIyNmE2MTFjZTdkNmU2NTUzNzQ1NGIyNDI0N2E0YWEwYSIsInN1YiI6ImF1dGh6LWFkbWluLXBhc3Nwb3J0IiwianRpIjoiYXV0aHotcGFzc3BvcnQtYWNjZXNzLXRva2VuIiwiaWF0IjoxNzIzNjI1ODk2LCJuYmYiOjE3MjM2MjU4OTYsImV4cCI6MTcyMzYyNzY5NiwidWlkIjoxMDIxMSwibmFtZSI6Ilx1NWYyMFx1NGUzOSIsImFwcGlkIjoiYXV0aHpfYWRtaW4ifQ.s061AEWy7WwoLobTE11sY_G_sSn_z7_XnkXg2HG8rTo"}
    response = {"status":200,'userInfo':{'token':'7832332','userId':'1'}}
    return JsonResponse(response)



def test(request):
    response = {}
    response['status']=0
    response['message'] = '模拟错误信息'
    return JsonResponse(response)

def home(request):
    print("home....")
    print(request.GET.get("pageId"))
    response = {}
    response['status'] = 200
    response['message'] = 'success'
    response['shop'] = [
        {"id":"001","name":"banner","price":12.3},
        {"id":"002","name":"apple","price":2.3},
        {"id":"003","name":"peel","price":20.8},
    ]
    response['img'] = ['http://127.0.0.1:8000/static/img/banner.jpg','http://127.0.0.1:8000/static/img/banner.jpg']
    return JsonResponse(response)

def reg(request):
    print("注册....")
    data = json.loads(request.body.decode("utf-8"))

    print(data)
    response = {}
    try:
        res = loginUser.objects.filter(name=data["username"], password=data["password"])
        print(res)
        if res:
            response['msg'] = "该用户已注册"
            response['code'] = 1
            return JsonResponse(response)
        else:
            print("**12")
            loginUser.objects.create(name=data["username"], password=data["password"])
            response['msg'] = "该用户注册成功"
            response['code'] = 0
            return JsonResponse(response)


    except Exception as e:
        print("**13")
        response['msg'] = str(e)
        response['code'] = 1


def articleList(request):
    response = {}
    data = [
        {
            "id": "1001",
            "cate_name": "生活",
            "cate_alias": "家庭伦理生活类型"
        },
        {
            "id": "1002",
            "cate_name": "政治",
            "cate_alias": "政治人文历史"
        },
    ]

    response["code"]=0
    response['data'] = data
    return JsonResponse(response)

from django.conf.urls.static import static
from django.conf import settings
import os
import base64
def addAticle(request):
    print("addAticle...")
    # data = json.loads(request.body.decode("utf-8"))
    print(request.body.decode())
    # file = request.FILES.get("image")
    # name = request.POST.get("name")
    # print(file)
    # print(name)
    path2 = os.path.join(settings.STATICFILES_DIRS[0], 'xx3.jpeg')
    print(path2)
    image_base64 = request.body.decode()
    print(type(image_base64))
    if image_base64:
        # 去掉 base64 图片数据中的前缀（如果有）
        image_base64 = image_base64.split(',')[1]
        print(image_base64)

        # 解码 base64 数据
        file = base64.b64decode(image_base64)

        print(file)

        if file:
            with open(path2, 'wb') as f:
                f.write(file)
    return JsonResponse({'code':0})
